<?php

declare (strict_types = 1);

namespace app\webadmin\controller;

use app\webadmin\BaseController;
use app\webadmin\model\AdminLog;
use app\webadmin\model\Chongfu;
use app\webadmin\model\JingmiduCg;
use app\webadmin\model\Junyunxing;
use app\webadmin\model\Wendingxing;
use app\webadmin\validate\AdminCheck;
use think\exception\ValidateException;
use think\facade\Db;
use think\facade\Session;
use app\webadmin\model\Duibidu;
use PhpOffice\PhpSpreadsheet\Calculation\Statistical;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Shared\Date as Shared;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;



class Api extends BaseController
{
    //上传文件
    public function upload()
    {
        $param = get_params();
		$sourse = 'file';
		if(isset($param['sourse'])){
			$sourse = $param['sourse'];
		}
		if($sourse == 'file' || $sourse == 'tinymce'){
			if(request()->file('file')){
				$file = request()->file('file');
			}
			else{
				return to_assign(1, '没有选择上传文件');
			}
		}
		else{
			if (request()->file('editormd-image-file')) {
				$file = request()->file('editormd-image-file');
			} else {
				return to_assign(1, '没有选择上传文件');
			}
		}
        // 获取上传文件的hash散列值
        $sha1 = $file->hash('sha1');
        $md5 = $file->hash('md5');
        $rule = [
            'image' => 'jpg,png,jpeg,gif',
            'doc' => 'doc,docx,ppt,pptx,xls,xlsx,pdf',
            'file' => 'zip,gz,apk,rar,tar',
        ];
        $fileExt = $rule['image'] . ',' . $rule['doc'] . ',' . $rule['file'];
        //1M=1024*1024=1048576字节
        $fileSize = 2 * 1024 * 1024;
        if (isset($param['type']) && $param['type']) {
            $fileExt = $rule[$param['type']];
        }
        if (isset($param['size']) && $param['size']) {
            $fileSize = $param['size'];
        }
        $validate = \think\facade\Validate::rule([
            'image' => 'require|fileSize:' . $fileSize . '|fileExt:' . $fileExt,
        ]);
        $file_check['image'] = $file;
        if (!$validate->check($file_check)) {
            return to_assign(1, $validate->getError());
        }
        // 日期前綴
        $dataPath = date('Ym');
        $use = 'thumb';
        $filename = \think\facade\Filesystem::disk('public')->putFile($dataPath, $file, function () use ($md5) {
            return $md5;
        });
        if ($filename) {
            //写入到附件表
            $data = [];
            $path = get_config('filesystem.disks.public.url');
            $data['filepath'] = $path . '/' . $filename;
            $data['name'] = $file->getOriginalName();
            $data['mimetype'] = $file->getOriginalMime();
            $data['fileext'] = $file->extension();
            $data['filesize'] = $file->getSize();
            $data['filename'] = $filename;
            $data['sha1'] = $sha1;
            $data['md5'] = $md5;
            $data['module'] = \think\facade\App::initialize()->http->getName();
            $data['action'] = app('request')->action();
            $data['uploadip'] = app('request')->ip();
            $data['create_time'] = time();
            $data['user_id'] = get_login_admin('id') ? get_login_admin('id') : 0;
            if ($data['module'] = 'admin') {
                //通过后台上传的文件直接审核通过
                $data['status'] = 1;
                $data['admin_id'] = $data['user_id'];
                $data['audit_time'] = time();
            }
            $data['use'] = request()->has('use') ? request()->param('use') : $use; //附件用处
            $res['id'] = Db::name('file')->insertGetId($data);
            $res['filepath'] = $data['filepath'];
            $res['name'] = $data['name'];
            $res['filename'] = $data['filename'];
            add_log('upload', $data['user_id'], $data);
			if($sourse == 'editormd'){
				//editormd编辑器上传返回
				return json(['success'=>1,'message'=>'上传成功','url'=>$data['filepath']]);
			}
			else if($sourse == 'tinymce'){
				//tinymce编辑器上传返回
				return json(['success'=>1,'message'=>'上传成功','location'=>$data['filepath']]);
			}
			else{
				//普通上传返回
				return to_assign(0, '上传成功', $res);
			}
        } else {
            return to_assign(1, '上传失败，请重试');
        }
    }

    //上传文件
    public function newupload()
    {
        $param = get_params();
        //var_dump($param);exit;
        $sourse = 'file';
        if(isset($param['sourse'])){
            $sourse = $param['sourse'];
        }
        if($sourse == 'file' || $sourse == 'tinymce'){
            if(request()->file('file')){
                $file = request()->file('file');
            }
            else{
                return to_assign(1, '没有选择上传文件');
            }
        }
        else{
            if (request()->file('editormd-image-file')) {
                $file = request()->file('editormd-image-file');
            } else {
                return to_assign(1, '没有选择上传文件');
            }
        }
        // 获取上传文件的hash散列值
        $sha1 = $file->hash('sha1');
        $md5 = $file->hash('md5');
        $rule = [
            'image' => 'jpg,png,jpeg,gif',
            'doc' => 'txt,doc,docx,ppt,pptx,xls,xlsx,pdf',
            'file' => 'zip,gz,7z,rar,tar,apk',
            'video' => 'mpg,mp4,mpeg,avi,wmv,mov,flv,m4v',
        ];
        $fileExt = $rule['image'] . ',' . $rule['doc'] . ',' . $rule['file'] . ',' . $rule['video'];
        //1M=1024*1024=1048576字节
        $fileSize = 100 * 1024 * 1024;
        if (isset($param['type']) && $param['type']) {
            $fileExt = $rule[$param['type']];
        }
        if (isset($param['size']) && $param['size']) {
            $fileSize = $param['size'];
        }
        $validate = \think\facade\Validate::rule([
            'image' => 'require|fileSize:' . $fileSize . '|fileExt:' . $fileExt,
        ]);
        $file_check['image'] = $file;
        if (!$validate->check($file_check)) {
            return to_assign(1, $validate->getError());
        }
        // 日期前綴
        $dataPath = '';
        $use = 'thumb';
        $filename = \think\facade\Filesystem::disk('apk')->putFile($dataPath, $file, function () use ($md5) {
            return $md5;
        });
        if ($filename) {
            //写入到附件表
            $data = [];
            $path = get_config('filesystem.disks.apk.url');
            $data['filepath'] = $path . '/' . $filename;
            $data['name'] = $file->getOriginalName();
            $data['mimetype'] = $file->getOriginalMime();
            $data['fileext'] = $file->extension();
            $data['filesize'] = $file->getSize();
            $data['filename'] = $filename;
            $data['sha1'] = $sha1;
            $data['md5'] = $md5;
            $data['module'] = \think\facade\App::initialize()->http->getName();
            $data['action'] = app('request')->action();
            $data['uploadip'] = app('request')->ip();
            $data['create_time'] = time();
            $data['user_id'] = get_login_admin('id') ? get_login_admin('id') : 0;
            if ($data['module'] = 'admin') {
                //通过后台上传的文件直接审核通过
                $data['status'] = 1;
                $data['admin_id'] = $data['user_id'];
                $data['audit_time'] = time();
            }
            $data['use'] = request()->has('use') ? request()->param('use') : $use; //附件用处
            $res['id'] = Db::name('file')->insertGetId($data);
            $res['filepath'] = $data['filepath'];
            $res['name'] = $data['name'];
            $res['filename'] = $data['filename'];
            $res['filesize'] = $data['filesize'];
            $res['fileext'] = $data['fileext'];
            add_log('upload', $data['user_id'], $data);
            if($sourse == 'editormd'){
                //editormd编辑器上传返回
                return json(['success'=>1,'message'=>'上传成功','url'=>$data['filepath']]);
            }
            else if($sourse == 'tinymce'){
                //tinymce编辑器上传返回
                return json(['success'=>1,'message'=>'上传成功','location'=>$data['filepath']]);
            }
            else{
                //普通上传返回
                return to_assign(0, '上传成功', $res);
            }
        } else {
            return to_assign(1, '上传失败，请重试');
        }
    }

    //上传资源文件
    public function newuploadresource()
    {
        $param = get_params();
        $sourse = 'file';
        if(isset($param['sourse'])){
            $sourse = $param['sourse'];
        }
        if($sourse == 'file' || $sourse == 'tinymce'){
            if(request()->file('file')){
                $file = request()->file('file');
            }
            else{
                return to_assign(1, '没有选择上传文件');
            }
        }
        else{
            if (request()->file('editormd-image-file')) {
                $file = request()->file('editormd-image-file');
            } else {
                return to_assign(1, '没有选择上传文件');
            }
        }
        // 获取上传文件的hash散列值
        $sha1 = $file->hash('sha1');
        $md5 = $file->hash('md5');
        $rule = [
            'image' => 'jpg,png,jpeg,gif',
            'doc' => 'txt,doc,docx,ppt,pptx,xls,xlsx,pdf',
            'file' => 'zip',
            'video' => 'mpg,mp4,mpeg,avi,wmv,mov,flv,m4v',
        ];
        $fileExt = $rule['image'] . ',' . $rule['doc'] . ',' . $rule['file'] . ',' . $rule['video'];
        //1M=1024*1024=1048576字节
        $fileSize = 100 * 1024 * 1024;
        if (isset($param['type']) && $param['type']) {
            $fileExt = $rule[$param['type']];
        }
        if (isset($param['size']) && $param['size']) {
            $fileSize = $param['size'];
        }
        $validate = \think\facade\Validate::rule([
            'image' => 'require|fileSize:' . $fileSize . '|fileExt:' . $fileExt,
        ]);
        $file_check['image'] = $file;
        if (!$validate->check($file_check)) {
            return to_assign(1, $validate->getError());
        }
        // 日期前綴
        $dataPath = '';
        $use = 'thumb';
        $filename = \think\facade\Filesystem::disk('public')->putFile($dataPath, $file, function () use ($md5) {
            return $md5;
        });
        if ($filename) {
            //写入到附件表
            $data = [];
            $path = get_config('filesystem.disks.public.url');
            $data['filepath'] = $path . '/' . $filename;
            $data['name'] = $file->getOriginalName();
            $data['mimetype'] = $file->getOriginalMime();
            $data['fileext'] = $file->extension();
            $data['filesize'] = $file->getSize();
            $data['filename'] = $filename;
            $data['sha1'] = $sha1;
            $data['md5'] = $md5;
            $data['module'] = \think\facade\App::initialize()->http->getName();
            $data['action'] = app('request')->action();
            $data['uploadip'] = app('request')->ip();
            $data['create_time'] = time();
            $data['user_id'] = get_login_admin('id') ? get_login_admin('id') : 0;
            if ($data['module'] = 'admin') {
                //通过后台上传的文件直接审核通过
                $data['status'] = 1;
                $data['admin_id'] = $data['user_id'];
                $data['audit_time'] = time();
            }
            $data['use'] = request()->has('use') ? request()->param('use') : $use; //附件用处
            $res['id'] = Db::name('file')->insertGetId($data);
            $res['filepath'] = $data['filepath'];
            $res['name'] = $data['name'];
            $res['filename'] = $data['filename'];
            $res['filesize'] = $data['filesize'];
            $res['fileext'] = $data['fileext'];
            add_log('upload', $data['user_id'], $data);
            if($sourse == 'editormd'){
                //editormd编辑器上传返回
                return json(['success'=>1,'message'=>'上传成功','url'=>$data['filepath']]);
            }
            else if($sourse == 'tinymce'){
                //tinymce编辑器上传返回
                return json(['success'=>1,'message'=>'上传成功','location'=>$data['filepath']]);
            }
            else{
                //普通上传返回
                return to_assign(0, '上传成功', $res);
            }
        } else {
            return to_assign(1, '上传失败，请重试');
        }
    }

    //获取权限树所需的节点列表
    public function get_rule()
    {
        $rule = get_admin_rule();
        $group = [];
        if (!empty(get_params('id'))) {
            $group = get_admin_group_info(get_params('id'))['rules'];
        }
        $list = create_tree_list(0, $rule, $group);
        return to_assign(0, '', $list);
    }

    //获取关键字
    public function get_keyword_cate()
    {
        $keyword = get_keywords();
        return to_assign(0, '', $keyword);
    }

    //获取话题
    public function get_topics_cate()
    {
        //$topic = get_topics();
        //return to_assign(0, '', $topic);
    }

    //清空缓存
    public function cache_clear()
    {
        \think\facade\Cache::clear();
        return to_assign(0, '系统缓存已清空');
    }

    //发送测试邮件
    public function email_to($email)
    {
        $name = empty(get_config('webconfig.admin_title')) ? '系统' : get_config('webconfig.admin_title');
        if (send_email($email, "一封来自{$name}的测试邮件。")) {
            return to_assign(0, '发送成功，请注意查收');
        }
        return to_assign(1, '发送失败');
    }

    //修改个人信息
    public function edit_personal()
    {
        return view('admin/edit_personal', [
            'admin' => get_login_admin(),
        ]);
    }

    //保存个人信息修改
    public function personal_submit()
    {
        if (request()->isAjax()) {
            $param = get_params();
            try {
                validate(AdminCheck::class)->scene('editPersonal')->check($param);
            } catch (ValidateException $e) {
                // 验证失败 输出错误信息
                return to_assign(1, $e->getError());
            }
            unset($param['username']);
            $uid = get_login_admin('id');
            Db::name('Admin')->where([
                'id' => $uid,
            ])->strict(false)->field(true)->update($param);
            $session_admin = get_config('app.session_admin');
            Session::set($session_admin, Db::name('admin')->find($uid));
            return to_assign();
        }
    }

    //修改密码
    public function edit_password()
    {
        return view('admin/edit_password', [
            'admin' => get_login_admin(),
        ]);
    }

    //保存密码修改
    public function password_submit()
    {
        if (request()->isAjax()) {
            $param = get_params();
            try {
                validate(AdminCheck::class)->scene('editpwd')->check($param);
            } catch (ValidateException $e) {
                // 验证失败 输出错误信息
                return to_assign(1, $e->getError());
            }
            $admin = get_login_admin();
            if (set_password($param['old_pwd'], $admin['salt']) !== $admin['pwd']) {
                return to_assign(1, '旧密码不正确!');
            }
            unset($param['username']);
            $param['salt'] = set_salt(20);
            $param['pwd'] = set_password($param['pwd'], $param['salt']);
            Db::name('Admin')->where([
                'id' => $admin['id'],
            ])->strict(false)->field(true)->update($param);
            $session_admin = get_config('app.session_admin');
            Session::set($session_admin, Db::name('admin')->find($admin['id']));
            return to_assign();
        }
    }

    // 测试邮件发送
    public function email_test()
    {
        $sender = get_params('email');
        //检查是否邮箱格式
        if (!is_email($sender)) {
            return to_assign(1, '测试邮箱码格式有误');
        }
        $email_config = \think\facade\Db::name('config')
            ->where('name', 'email')
            ->find();
        $config = unserialize($email_config['content']);
        $content = $config['template'];
        //所有项目必须填写
        if (empty($config['smtp']) || empty($config['smtp_port']) || empty($config['smtp_user']) || empty($config['smtp_pwd'])) {
            return to_assign(1, '请完善邮件配置信息！');
        }

        $send = send_email($sender, '测试邮件', $content);
        if ($send) {
            return to_assign(0, '邮件发送成功！');
        } else {
            return to_assign(1, '邮件发送失败！');
        }
    }

    //首页获取
    public function get_admin_list()
    {
        $content = Db::name('Admin')
            ->where(['status' => 1])
            ->order('id desc')
            ->limit(10)
            ->select()->toArray();
        $res['data'] = $content;
        return table_assign(0, '', $res);
    }


    //首页获取最新10条用户
    public function get_topuser_list()
    {
        $user_list = \app\webadmin\model\Users::where('status',1)
            ->field("id,nickname,mobile,avatar,create_time")
            ->order('id desc')
            ->paginate(10, false, null)->each(function ($item, $k) {
                $item['createdate']=date('Y-m-d H:i:s',$item->create_time);
                return $item;
            });
        return table_assign(0, '', $user_list);
    }

    //稳定性列表
    public function get_wendingxing_list(){
        $wdx_list = \app\webadmin\model\Wendingxing::
            field("id,times,datas")
            ->order('id asc')
            ->paginate(10, false, null)->each(function ($item, $k) {
                 return $item;
            });
        return table_assign(0, '', $wdx_list);
    }

    public function get_chongfu_list(){
        $wdx_list = \app\webadmin\model\Chongfu::
            order('id asc')
            ->paginate(10, false, null)->each(function ($item, $k) {
                return $item;
            });
        return table_assign(0, '', $wdx_list);
    }


    //系统操作日志
    public function log_list()
    {
        return view('admin/log_list');
    }

    //获取系统操作日志
    public function get_log_list()
    {
        $param = get_params();
        $log = new AdminLog();
        $content = $log->get_log_list($param);
        return table_assign(0, '', $content);
    }

    //获取访问记录
    public function get_view_data()
    {
        $param = get_params();
        $first_time = time();
        $second_time = $first_time - 86400;
        $three_time = $first_time - 86400*365;
        $begin_first = strtotime(date('Y-m-d', $first_time) . " 00:00:00");
        $end_first = strtotime(date('Y-m-d', $first_time) . " 23:59:59");
        $begin_second = strtotime(date('Y-m-d', $second_time) . " 00:00:00");
        $end_second = strtotime(date('Y-m-d', $second_time) . " 23:59:59");
		$begin_three = strtotime(date('Y-m-d', $three_time) . " 00:00:00");
        $data_first = Db::name('AdminLog')->field('create_time')->whereBetween('create_time', "$begin_first,$end_first")->select();
        $data_second = Db::name('AdminLog')->field('create_time')->whereBetween('create_time', "$begin_second,$end_second")->select();

		$data_three = Db::name('AdminLog')->field('create_time')->whereBetween('create_time', "$begin_three,$end_first")->select();

        return to_assign(0, '', ['data_first' => hour_document($data_first), 'data_second' => hour_document($data_second), 'data_three'=>date_document($data_three)]);
    }


    //导入对比度表
    public function import_duibidu(){
        // 获取表单上传文件
        $file[]= request()->file('file');

        try {
            // 验证文件大小，名称等是否正确
            validate(['file' => 'filesize:51200|fileExt:xls,xlsx'])->check($file);
            // 日期前綴
            $dataPath = date('Ym');
            $md5 = $file[0]->hash('md5');
            $savename = \think\facade\Filesystem::disk('public')->putFile($dataPath, $file[0], function () use ($md5) {
                return $md5;
            });
            $fileExtendName = substr(strrchr($savename, '.'), 1);
            // 有Xls和Xlsx格式两种
            if ($fileExtendName == 'xlsx') {
                $objReader = IOFactory::createReader('Xlsx');
            } else {
                $objReader = IOFactory::createReader('Xls');
            }
            $objReader->setReadDataOnly(TRUE);
            $path = get_config('filesystem.disks.public.url');
            // 读取文件，tp6默认上传的文件，在runtime的相应目录下，可根据实际情况自己更改
            $objPHPExcel = $objReader->load('.'.$path . '/' .$savename);
            $sheet = $objPHPExcel->getSheet(0);   //excel中的第一张sheet
            $highestRow = $sheet->getHighestRow();       // 取得总行数
            $highestColumn = $sheet->getHighestColumn();   // 取得总列数
            Coordinate::columnIndexFromString($highestColumn);
            $lines = $highestRow - 1;
            if ($lines <= 0) {
                return to_assign(1, '数据不能为空');
                exit();
            }
            $data=[];
            //循环读取excel表格，整合成数组。如果是不指定key的二维，就用$data[i][j]表示。
            for ($j = 2; $j <= $highestRow; $j++) {

                $codes = $objPHPExcel->getActiveSheet()->getCell("B" . $j)->getValue();
                if(empty($codes)){
                    continue;
                }
                $name = $objPHPExcel->getActiveSheet()->getCell("C" . $j)->getValue();
                if(empty($name)){
                    continue;
                }

                $ssdate=$objPHPExcel->getActiveSheet()->getCell("G" . $j)->getValue();
                //\think\facade\Log::info('ssdate='.$ssdate);
                if($ssdate!=''){
                    $shishi_date = strtotime(excelTime($ssdate));
                }else{
                    $shishi_date='0';
                }
                $jieludate=$objPHPExcel->getActiveSheet()->getCell("D" . $j)->getValue();
                if($jieludate!=''){
                    $jielu_date = strtotime(excelTime($jieludate));
                }else{
                    $jielu_date='0';
                }
                //\think\facade\Log::info('jieludate='.$jieludate);
                $jizhundate=$objPHPExcel->getActiveSheet()->getCell("E" . $j)->getValue();
                if($jizhundate!=''){
                    $jizhun_date = strtotime(excelTime($jizhundate));
                }else{
                    $jizhun_date='0';
                }
                $price = $objPHPExcel->getActiveSheet()->getCell("F" . $j)->getValue();

                $count_name = Db::name('Duibidu')->where('codes',$codes)->count();
                if($count_name>0){

                    $param['update_time'] = time();
                    $param['shishi_date']=$shishi_date;
                    $param['jizhun_date']=$jizhun_date;
                    $param['jielu_date']=$jielu_date;
                    $param['price']=$price;
                    Duibidu::where('codes',$codes)->update($param);
                    continue;
                    //return to_assign(1, '第'.($j - 2).'行的股票代码已经存在');
                }

                $data[$j - 2] = [
                    'codes' => $codes,
                    'name' => $name,
                    'shishi_date' => $shishi_date,
                    'jielu_date' => $jielu_date,
                    'jizhun_date' => $jizhun_date,
                    'price' => $price,
                ];
            }

            $count=0;
            //\think\facade\Log::info('data='.json_encode($data));
            if($data){
                foreach ($data as $a => $aa) {
                    $cid = Duibidu::strict(false)->field(true)->insertGetId($aa);
                    if($cid>0){
                        $count++;
                    }
                }
                return to_assign(0, '共成功导入了'.$count.'条数据');
            }else{
                return to_assign(0, '操作成功');
            }
        } catch (\think\exception\ValidateException $e) {
            return to_assign(1, $e->getMessage());
        }
    }

    //导入稳定性
    public function import_wendingxing(){
        // 获取表单上传文件
        $file[]= request()->file('file');

        try {
            // 验证文件大小，名称等是否正确
            validate(['file' => 'filesize:51200|fileExt:xls,xlsx'])->check($file);
            // 日期前綴
            $dataPath = date('Ym');
            $md5 = $file[0]->hash('md5');
            $savename = \think\facade\Filesystem::disk('public')->putFile($dataPath, $file[0], function () use ($md5) {
                return $md5;
            });
            $fileExtendName = substr(strrchr($savename, '.'), 1);
            // 有Xls和Xlsx格式两种
            if ($fileExtendName == 'xlsx') {
                $objReader = IOFactory::createReader('Xlsx');
            } else {
                $objReader = IOFactory::createReader('Xls');
            }
            $objReader->setReadDataOnly(TRUE);
            $path = get_config('filesystem.disks.public.url');
            // 读取文件，tp6默认上传的文件，在runtime的相应目录下，可根据实际情况自己更改
            $objPHPExcel = $objReader->load('.'.$path . '/' .$savename);
            $sheet = $objPHPExcel->getSheet(0);   //excel中的第一张sheet
            $highestRow = $sheet->getHighestRow();       // 取得总行数
            $highestColumn = $sheet->getHighestColumn();   // 取得总列数
            Coordinate::columnIndexFromString($highestColumn);
            $lines = $highestRow - 1;
            if ($lines <= 0) {
                return to_assign(1, '数据不能为空');
                exit();
            }
            $data=[];
            //循环读取excel表格，整合成数组。如果是不指定key的二维，就用$data[i][j]表示。
            for ($j = 2; $j <= $highestRow; $j++) {

                $times = $objPHPExcel->getActiveSheet()->getCell("A" . $j)->getValue();
                /*if(empty($times)){
                    continue;
                }*/
                $datas = $objPHPExcel->getActiveSheet()->getCell("B" . $j)->getValue();
                if(empty($datas)){
                    continue;
                }

                $count_name = Db::name('Wendingxing')->where('times',$times)->count();
                if($count_name>0){

                    $param['update_time'] = time();
                    $param['times']=$times;
                    $param['datas']=$datas;
                    Wendingxing::where('times',$times)->update($param);
                    continue;
                    //return to_assign(1, '第'.($j - 2).'行的股票代码已经存在');
                }

                $data[$j - 2] = [
                    'uid'=>get_login_admin('id'),
                    'times' => $times,
                    'datas' => $datas,
                    'create_time'=>time()
                ];
            }

            $count=0;
            if($data){
                foreach ($data as $a => $aa) {
                    $cid = Wendingxing::strict(false)->field(true)->insertGetId($aa);
                    if($cid>0){
                        $count++;
                    }
                }
                return to_assign(0, '共成功导入了'.$count.'条数据');
            }else{
                return to_assign(0, '操作成功');
            }
        } catch (\think\exception\ValidateException $e) {
            return to_assign(1, $e->getMessage());
        }
    }

    //导入重复次数
    public function import_chongfu(){
        // 获取表单上传文件
        $file[]= request()->file('file');

        try {
            // 验证文件大小，名称等是否正确
            validate(['file' => 'filesize:51200|fileExt:xls,xlsx'])->check($file);
            // 日期前綴
            $dataPath = date('Ym');
            $md5 = $file[0]->hash('md5');
            $savename = \think\facade\Filesystem::disk('public')->putFile($dataPath, $file[0], function () use ($md5) {
                return $md5;
            });
            $fileExtendName = substr(strrchr($savename, '.'), 1);
            // 有Xls和Xlsx格式两种
            if ($fileExtendName == 'xlsx') {
                $objReader = IOFactory::createReader('Xlsx');
            } else {
                $objReader = IOFactory::createReader('Xls');
            }
            $objReader->setReadDataOnly(TRUE);
            $path = get_config('filesystem.disks.public.url');
            // 读取文件，tp6默认上传的文件，在runtime的相应目录下，可根据实际情况自己更改
            $objPHPExcel = $objReader->load('.'.$path . '/' .$savename);
            $sheet = $objPHPExcel->getSheet(0);   //excel中的第一张sheet
            $highestRow = $sheet->getHighestRow();       // 取得总行数
            $highestColumn = $sheet->getHighestColumn();   // 取得总列数
            Coordinate::columnIndexFromString($highestColumn);
            $lines = $highestRow - 1;
            if ($lines <= 0) {
                return to_assign(1, '数据不能为空');
                exit();
            }
            $data=[];
            //循环读取excel表格，整合成数组。如果是不指定key的二维，就用$data[i][j]表示。
            for ($j = 2; $j <= $highestRow; $j++) {

                $cishu = $objPHPExcel->getActiveSheet()->getCell("A" . $j)->getValue();
                if(empty($cishu)){
                    continue;
                }
                $data1 = $objPHPExcel->getActiveSheet()->getCell("B" . $j)->getValue();
                $data2 = $objPHPExcel->getActiveSheet()->getCell("C" . $j)->getValue();
                $data3 = $objPHPExcel->getActiveSheet()->getCell("D" . $j)->getValue();
                $data4 = $objPHPExcel->getActiveSheet()->getCell("E" . $j)->getValue();
                $data5 = $objPHPExcel->getActiveSheet()->getCell("F" . $j)->getValue();
                $data6 = $objPHPExcel->getActiveSheet()->getCell("G" . $j)->getValue();

                //合计
                $sum=$data1+$data2+$data3+$data4+$data5+$data6;
                //平均值
                $avg=round($sum/6,2);
                $stdDev = Statistical::STDEV(array($data1,$data2,$data3,$data4,$data5,$data6));

                $data[$j - 2] = [
                    'cishu' => $cishu,
                    'uid'=>get_login_admin('id'),
                    'data1' => $data1,
                    'data2' => $data2,
                    'data3' => $data3,
                    'data4' => $data4,
                    'data5' => $data5,
                    'data6' => $data6,
                    'avgs'=>$avg,
                    'sds'=>$stdDev,
                    'create_time'=>time()
                ];
            }

            $count=0;
            if($data){
                foreach ($data as $a => $aa) {
                    $cid = Chongfu::strict(false)->field(true)->insertGetId($aa);
                    if($cid>0){
                        $count++;
                    }
                }
                return to_assign(0, '共成功导入了'.$count.'条数据');
            }else{
                return to_assign(0, '操作成功');
            }
        } catch (\think\exception\ValidateException $e) {
            return to_assign(1, $e->getMessage());
        }
    }

    //导入均匀性
    public function import_junyunxing(){
        // 获取表单上传文件
        $file[]= request()->file('file');

        try {
            // 验证文件大小，名称等是否正确
            validate(['file' => 'filesize:51200|fileExt:xls,xlsx'])->check($file);
            // 日期前綴
            $dataPath = date('Ym');
            $md5 = $file[0]->hash('md5');
            $savename = \think\facade\Filesystem::disk('public')->putFile($dataPath, $file[0], function () use ($md5) {
                return $md5;
            });
            $fileExtendName = substr(strrchr($savename, '.'), 1);
            // 有Xls和Xlsx格式两种
            if ($fileExtendName == 'xlsx') {
                $objReader = IOFactory::createReader('Xlsx');
            } else {
                $objReader = IOFactory::createReader('Xls');
            }
            $objReader->setReadDataOnly(TRUE);
            $path = get_config('filesystem.disks.public.url');
            // 读取文件，tp6默认上传的文件，在runtime的相应目录下，可根据实际情况自己更改
            $objPHPExcel = $objReader->load('.'.$path . '/' .$savename);
            $sheet = $objPHPExcel->getSheet(0);   //excel中的第一张sheet
            $highestRow = $sheet->getHighestRow();       // 取得总行数
            $highestColumn = $sheet->getHighestColumn();   // 取得总列数
            Coordinate::columnIndexFromString($highestColumn);
            $lines = $highestRow - 1;
            if ($lines <= 0) {
                return to_assign(1, '数据不能为空');
                exit();
            }
            $data=[];
            //循环读取excel表格，整合成数组。如果是不指定key的二维，就用$data[i][j]表示。
            for ($j = 2; $j <= $highestRow; $j++) {

                $nums = $objPHPExcel->getActiveSheet()->getCell("A" . $j)->getValue();
                if(empty($nums)){
                    continue;
                }
                $yp1 = $objPHPExcel->getActiveSheet()->getCell("B" . $j)->getValue();
                $yp2 = $objPHPExcel->getActiveSheet()->getCell("C" . $j)->getValue();
                $yp3 = $objPHPExcel->getActiveSheet()->getCell("D" . $j)->getValue();

                //合计
                $sum=$yp1+$yp2+$yp3;
                $sum_pf=sum_pingfang([$yp1,$yp2,$yp3]);
                $data3=pow($sum,2);
                $data[$j - 2] = [
                    'nums' => $nums,
                    'uid'=>get_login_admin('id'),
                    'yp1' => $yp1,
                    'yp2' => $yp2,
                    'yp3' => $yp3,
                    'data1' => $sum,
                    'data2' => $sum_pf,
                    'data3' => $data3,
                    'create_time'=>time()
                ];
                \think\facade\Log::info('data='.json_encode($data));
            }

            $count=0;
            \think\facade\Log::info('data='.json_encode($data));
            if($data){
                foreach ($data as $a => $aa) {
                    $cid = Junyunxing::strict(false)->field(true)->insertGetId($aa);
                    if($cid>0){
                        $count++;
                    }
                }
                return to_assign(0, '共成功导入了'.$count.'条数据');
            }else{
                return to_assign(0, '操作成功');
            }
        } catch (\think\exception\ValidateException $e) {
            return to_assign(1, $e->getMessage());
        }
    }

    //导入数据检验9家
    public function import_sjjy(){
        // 获取表单上传文件
        $file[]= request()->file('file');
        try {
            // 验证文件大小，名称等是否正确
            validate(['file' => 'filesize:51200|fileExt:xls,xlsx'])->check($file);
            // 日期前綴
            $dataPath = date('Ym');
            $md5 = $file[0]->hash('md5');
            $savename = \think\facade\Filesystem::disk('public')->putFile($dataPath, $file[0], function () use ($md5) {
                return $md5;
            });
            $fileExtendName = substr(strrchr($savename, '.'), 1);
            // 有Xls和Xlsx格式两种
            if ($fileExtendName == 'xlsx') {
                $objReader = IOFactory::createReader('Xlsx');
            } else {
                $objReader = IOFactory::createReader('Xls');
            }
            $objReader->setReadDataOnly(TRUE);
            $path = get_config('filesystem.disks.public.url');
            // 读取文件，tp6默认上传的文件，在runtime的相应目录下，可根据实际情况自己更改
            $objPHPExcel = $objReader->load('.'.$path . '/' .$savename);
            $sheet = $objPHPExcel->getSheet(0);   //excel中的第一张sheet
            $highestRow = $sheet->getHighestRow();       // 取得总行数
            $highestColumn = $sheet->getHighestColumn();   // 取得总列数
            Coordinate::columnIndexFromString($highestColumn);
            $lines = $highestRow - 1;
            if ($lines <= 0) {
                return to_assign(1, '数据不能为空');
                exit();
            }
            $data=[];
            //循环读取excel表格，整合成数组。如果是不指定key的二维，就用$data[i][j]表示。
            for ($j = 2; $j <= $highestRow; $j++) {

                $nums = $objPHPExcel->getActiveSheet()->getCell("A" . $j)->getValue();
                if(empty($nums)){
                    continue;
                }
                $data1 = $objPHPExcel->getActiveSheet()->getCell("B" . $j)->getValue();
                $data2 = $objPHPExcel->getActiveSheet()->getCell("C" . $j)->getValue();
                $data3 = $objPHPExcel->getActiveSheet()->getCell("D" . $j)->getValue();
                $data4 = $objPHPExcel->getActiveSheet()->getCell("E" . $j)->getValue();
                $data5 = $objPHPExcel->getActiveSheet()->getCell("F" . $j)->getValue();
                $data6 = $objPHPExcel->getActiveSheet()->getCell("G" . $j)->getValue();
                $data7 = $objPHPExcel->getActiveSheet()->getCell("H" . $j)->getValue();
                $data8 = $objPHPExcel->getActiveSheet()->getCell("I" . $j)->getValue();

                //合计
                $sum=$data1+$data2+$data3+$data4+$data5+$data6+$data7+$data8;
                $avgs=round($sum/8,3);
                //$sum_pf=sum_pingfang([$yp1,$yp2,$yp3]);
                //=STDEV(C3:J3)
                $stdDev = Statistical::STDEV(array($data1,$data2,$data3,$data4,$data5,$data6,$data7,$data8));
                //=O3/N3*100
                $rsd=$stdDev/$avgs*100;
                $data[$j - 2] = [
                    'nums' => $nums,
                    'type'=>1,
                    'uid'=>get_login_admin('id'),
                    'data1' => $data1,
                    'data2' => $data2,
                    'data3' => $data3,
                    'data4' => $data4,
                    'data5' => $data5,
                    'data6' => $data6,
                    'data7' => $data7,
                    'data8' => $data8,
                    'avgs' => $avgs,
                    'sds' => $stdDev,
                    'rsd' => $rsd,
                    'create_time'=>time()
                ];
                \think\facade\Log::info('data='.json_encode($data));
            }

            $count=0;
            \think\facade\Log::info('data='.json_encode($data));
            if($data){
                foreach ($data as $a => $aa) {
                    $cid = \app\webadmin\model\Sjjy::strict(false)->field(true)->insertGetId($aa);
                    if($cid>0){
                        $count++;
                    }
                }
                return to_assign(0, '共成功导入了'.$count.'条数据');
            }else{
                return to_assign(0, '操作成功');
            }
        } catch (\think\exception\ValidateException $e) {
            return to_assign(1, $e->getMessage());
        }
    }

    //导入数据检验10家
    public function import_sjjy_ten(){
        // 获取表单上传文件
        $file[]= request()->file('file');
        try {
            // 验证文件大小，名称等是否正确
            validate(['file' => 'filesize:51200|fileExt:xls,xlsx'])->check($file);
            // 日期前綴
            $dataPath = date('Ym');
            $md5 = $file[0]->hash('md5');
            $savename = \think\facade\Filesystem::disk('public')->putFile($dataPath, $file[0], function () use ($md5) {
                return $md5;
            });
            $fileExtendName = substr(strrchr($savename, '.'), 1);
            // 有Xls和Xlsx格式两种
            if ($fileExtendName == 'xlsx') {
                $objReader = IOFactory::createReader('Xlsx');
            } else {
                $objReader = IOFactory::createReader('Xls');
            }
            $objReader->setReadDataOnly(TRUE);
            $path = get_config('filesystem.disks.public.url');
            // 读取文件，tp6默认上传的文件，在runtime的相应目录下，可根据实际情况自己更改
            $objPHPExcel = $objReader->load('.'.$path . '/' .$savename);
            $sheet = $objPHPExcel->getSheet(0);   //excel中的第一张sheet
            $highestRow = $sheet->getHighestRow();       // 取得总行数
            $highestColumn = $sheet->getHighestColumn();   // 取得总列数
            Coordinate::columnIndexFromString($highestColumn);
            $lines = $highestRow - 1;
            if ($lines <= 0) {
                return to_assign(1, '数据不能为空');
                exit();
            }
            $data=[];
            //循环读取excel表格，整合成数组。如果是不指定key的二维，就用$data[i][j]表示。
            for ($j = 2; $j <= $highestRow; $j++) {

                $nums = $objPHPExcel->getActiveSheet()->getCell("A" . $j)->getValue();
                if(empty($nums)){
                    continue;
                }
                $data1 = $objPHPExcel->getActiveSheet()->getCell("B" . $j)->getValue();
                $data2 = $objPHPExcel->getActiveSheet()->getCell("C" . $j)->getValue();
                $data3 = $objPHPExcel->getActiveSheet()->getCell("D" . $j)->getValue();
                $data4 = $objPHPExcel->getActiveSheet()->getCell("E" . $j)->getValue();
                $data5 = $objPHPExcel->getActiveSheet()->getCell("F" . $j)->getValue();
                $data6 = $objPHPExcel->getActiveSheet()->getCell("G" . $j)->getValue();
                $data7 = $objPHPExcel->getActiveSheet()->getCell("H" . $j)->getValue();
                $data8 = $objPHPExcel->getActiveSheet()->getCell("I" . $j)->getValue();

                //合计
                $sum=$data1+$data2+$data3+$data4+$data5+$data6+$data7+$data8;
                $avgs=round($sum/8,3);
                //$sum_pf=sum_pingfang([$yp1,$yp2,$yp3]);
                //=STDEV(C3:J3)
                $stdDev = Statistical::STDEV(array($data1,$data2,$data3,$data4,$data5,$data6,$data7,$data8));
                //=O3/N3*100
                $rsd=$stdDev/$avgs*100;
                //$data3=pow($sum,2);
                $data[$j - 2] = [
                    'nums' => $nums,
                    'type'=>2,
                    'uid'=>get_login_admin('id'),
                    'data1' => $data1,
                    'data2' => $data2,
                    'data3' => $data3,
                    'data4' => $data4,
                    'data5' => $data5,
                    'data6' => $data6,
                    'data7' => $data7,
                    'data8' => $data8,
                    'avgs' => $avgs,
                    'sds' => $stdDev,
                    'rsd' => $rsd,
                    'create_time'=>time()
                ];
                //\think\facade\Log::info('data='.json_encode($data));
            }

            $count=0;
            //\think\facade\Log::info('data='.json_encode($data));
            if($data){
                foreach ($data as $a => $aa) {
                    $cid = \app\webadmin\model\Sjjy::strict(false)->field(true)->insertGetId($aa);
                    if($cid>0){
                        $count++;
                    }
                }
                return to_assign(0, '共成功导入了'.$count.'条数据');
            }else{
                return to_assign(0, '操作成功');
            }
        } catch (\think\exception\ValidateException $e) {
            return to_assign(1, $e->getMessage());
        }
    }

    //导入常规样品评定测量
    public function import_jingmidu_cg(){
        // 获取表单上传文件
        $file[]= request()->file('file');

        try {
            // 验证文件大小，名称等是否正确
            validate(['file' => 'filesize:51200|fileExt:xls,xlsx'])->check($file);
            // 日期前綴
            $dataPath = date('Ym');
            $md5 = $file[0]->hash('md5');
            $savename = \think\facade\Filesystem::disk('public')->putFile($dataPath, $file[0], function () use ($md5) {
                return $md5;
            });
            $fileExtendName = substr(strrchr($savename, '.'), 1);
            // 有Xls和Xlsx格式两种
            if ($fileExtendName == 'xlsx') {
                $objReader = IOFactory::createReader('Xlsx');
            } else {
                $objReader = IOFactory::createReader('Xls');
            }
            $objReader->setReadDataOnly(TRUE);
            $path = get_config('filesystem.disks.public.url');
            // 读取文件，tp6默认上传的文件，在runtime的相应目录下，可根据实际情况自己更改
            $objPHPExcel = $objReader->load('.'.$path . '/' .$savename);
            $sheet = $objPHPExcel->getSheet(0);   //excel中的第一张sheet
            $highestRow = $sheet->getHighestRow();       // 取得总行数
            $highestColumn = $sheet->getHighestColumn();   // 取得总列数
            Coordinate::columnIndexFromString($highestColumn);
            $lines = $highestRow - 1;
            if ($lines <= 0) {
                return to_assign(1, '数据不能为空');
                exit();
            }
            $data=[];
            //循环读取excel表格，整合成数组。如果是不指定key的二维，就用$data[i][j]表示。
            for ($j = 2; $j <= $highestRow; $j++) {

                $nums = $objPHPExcel->getActiveSheet()->getCell("A" . $j)->getValue();
                if(empty($nums)){
                    continue;
                }
                $data1 = $objPHPExcel->getActiveSheet()->getCell("B" . $j)->getValue();
                $data2 = $objPHPExcel->getActiveSheet()->getCell("C" . $j)->getValue();
                //绝对值
                $jueduizhi=abs(floatval($data1)-floatval($data2));
                $averages=Statistical::AVERAGE([$data1,$data2]);
                //相对差值的绝对值 =D10/E10
                $xiangduizhi=sprint_data($jueduizhi/$averages,3);
                $data[$j - 2] = [
                    'nums' => $nums,
                    'uid'=>get_login_admin('id'),
                    'data1' => $data1,
                    'data2' => $data2,
                    'jueduizhi' => $jueduizhi,
                    'avgs'=>$averages,
                    'xiangduizhi'=>$xiangduizhi,
                    'create_time'=>time()
                ];
                //\think\facade\Log::info('data='.json_encode($data));
            }

            $count=0;
            //\think\facade\Log::info('data='.json_encode($data));
            if($data){
                foreach ($data as $a => $aa) {
                    $cid = JingmiduCg::strict(false)->field(true)->insertGetId($aa);
                    if($cid>0){
                        $count++;
                    }
                }
                return to_assign(0, '共成功导入了'.$count.'条数据');
            }else{
                return to_assign(0, '操作成功');
            }
        } catch (\think\exception\ValidateException $e) {
            return to_assign(1, $e->getMessage());
        }
    }

    //导入标准物质评定模版
    public function import_jingmidu_wz(){
        // 获取表单上传文件
        $file[]= request()->file('file');

        try {
            // 验证文件大小，名称等是否正确
            validate(['file' => 'filesize:51200|fileExt:xls,xlsx'])->check($file);
            // 日期前綴
            $dataPath = date('Ym');
            $md5 = $file[0]->hash('md5');
            $savename = \think\facade\Filesystem::disk('public')->putFile($dataPath, $file[0], function () use ($md5) {
                return $md5;
            });
            $fileExtendName = substr(strrchr($savename, '.'), 1);
            // 有Xls和Xlsx格式两种
            if ($fileExtendName == 'xlsx') {
                $objReader = IOFactory::createReader('Xlsx');
            } else {
                $objReader = IOFactory::createReader('Xls');
            }
            $objReader->setReadDataOnly(TRUE);
            $path = get_config('filesystem.disks.public.url');
            // 读取文件，tp6默认上传的文件，在runtime的相应目录下，可根据实际情况自己更改
            $objPHPExcel = $objReader->load('.'.$path . '/' .$savename);
            $sheet = $objPHPExcel->getSheet(0);   //excel中的第一张sheet
            $highestRow = $sheet->getHighestRow();       // 取得总行数
            $highestColumn = $sheet->getHighestColumn();   // 取得总列数
            Coordinate::columnIndexFromString($highestColumn);
            $lines = $highestRow - 1;
            if ($lines <= 0) {
                return to_assign(1, '数据不能为空');
                exit();
            }
            $data=[];
            //循环读取excel表格，整合成数组。如果是不指定key的二维，就用$data[i][j]表示。
            for ($j = 3; $j <= $highestRow; $j++) {

                $nums = $objPHPExcel->getActiveSheet()->getCell("A" . $j)->getValue();
                if(empty($nums)){
                    continue;
                }
                $data1 = $objPHPExcel->getActiveSheet()->getCell("B" . $j)->getValue();
                $data2 = $objPHPExcel->getActiveSheet()->getCell("C" . $j)->getValue();
                $data3 = $objPHPExcel->getActiveSheet()->getCell("D" . $j)->getValue();
                $data4 = $objPHPExcel->getActiveSheet()->getCell("E" . $j)->getValue();
                $data5 = $objPHPExcel->getActiveSheet()->getCell("F" . $j)->getValue();

                $averages=Statistical::AVERAGE([$data1,$data2,$data3,$data4,$data5]);
                $data[$j - 2] = [
                    'nums' => $nums,
                    'uid'=>get_login_admin('id'),
                    'data1' => $data1,
                    'data2' => $data2,
                    'data3' => $data3,
                    'data4'=>$data4,
                    'data5'=>$data5,
                    'mean'=>$averages,
                    'create_time'=>time()
                ];
                //\think\facade\Log::info('data='.json_encode($data));
            }

            $count=0;
            //\think\facade\Log::info('data='.json_encode($data));
            if($data){
                foreach ($data as $a => $aa) {
                    $cid = \app\webadmin\model\JingmiduWz::strict(false)->field(true)->insertGetId($aa);
                    if($cid>0){
                        $count++;
                    }
                }
                return to_assign(0, '共成功导入了'.$count.'条数据');
            }else{
                return to_assign(0, '操作成功');
            }
        } catch (\think\exception\ValidateException $e) {
            return to_assign(1, $e->getMessage());
        }
    }

    //导入偏移不确定度-标准物质
    public function import_pianyidu(){
        // 获取表单上传文件
        $file[]= request()->file('file');

        try {
            // 验证文件大小，名称等是否正确
            validate(['file' => 'filesize:51200|fileExt:xls,xlsx'])->check($file);
            // 日期前綴
            $dataPath = date('Ym');
            $md5 = $file[0]->hash('md5');
            $savename = \think\facade\Filesystem::disk('public')->putFile($dataPath, $file[0], function () use ($md5) {
                return $md5;
            });
            $fileExtendName = substr(strrchr($savename, '.'), 1);
            // 有Xls和Xlsx格式两种
            if ($fileExtendName == 'xlsx') {
                $objReader = IOFactory::createReader('Xlsx');
            } else {
                $objReader = IOFactory::createReader('Xls');
            }
            $objReader->setReadDataOnly(TRUE);
            $path = get_config('filesystem.disks.public.url');
            // 读取文件，tp6默认上传的文件，在runtime的相应目录下，可根据实际情况自己更改
            $objPHPExcel = $objReader->load('.'.$path . '/' .$savename);
            $sheet = $objPHPExcel->getSheet(0);   //excel中的第一张sheet
            $highestRow = $sheet->getHighestRow();       // 取得总行数
            $highestColumn = $sheet->getHighestColumn();   // 取得总列数
            Coordinate::columnIndexFromString($highestColumn);
            $lines = $highestRow - 1;
            if ($lines <= 0) {
                return to_assign(1, '数据不能为空');
                exit();
            }
            $data=[];
            $data1 = $objPHPExcel->getActiveSheet()->getCell("A2" )->getValue();
            $data2 = $objPHPExcel->getActiveSheet()->getCell("B2")->getValue();
            $data3 = $objPHPExcel->getActiveSheet()->getCell("C2")->getValue();
            $bzz = $objPHPExcel->getActiveSheet()->getCell("A5")->getValue();
            $kzbqdd = $objPHPExcel->getActiveSheet()->getCell("B5")->getValue();


            $data[] = [
                'uid'=>get_login_admin('id'),
                'data1' => $data1,
                'data2' => $data2,
                'data3' => $data3,
                'bzz'=>$bzz,
                'kzbqdd'=>$kzbqdd,
                'create_time'=>time()
            ];

            $count=0;
            //\think\facade\Log::info('data='.json_encode($data));
            if($data){
                foreach ($data as $a => $aa) {
                    $cid = \app\webadmin\model\PianyiduBz::strict(false)->field(true)->insertGetId($aa);
                    if($cid>0){
                        $count++;
                    }
                }
                return to_assign(0, '共成功导入了'.$count.'条数据');
            }else{
                return to_assign(0, '操作成功');
            }
        } catch (\think\exception\ValidateException $e) {
            return to_assign(1, $e->getMessage());
        }
    }
}
